﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace PaiBanDaPing
{
    /// <summary>
    /// ScreenListCtrl.xaml 的交互逻辑
    /// </summary>
    public partial class ScreenListCtrl : UserControl
    {
        private ScreenListCtrlViewModel _model = new ScreenListCtrlViewModel();
        DispatcherTimer timer = new DispatcherTimer();

        public ScreenListCtrl()
        {
            InitializeComponent();
            this.DataContext = _model;
            timer.Interval = TimeSpan.FromSeconds(2);
            timer.Tick += Timer_Tick;
            timer.IsEnabled = true;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            _model.GetScreens();
            Dictionary<string, DaPingDisplayWin> tempDic = new Dictionary<string, DaPingDisplayWin>();
            foreach (var screen in _model.ScreenList)
            {
                if (ScreenManger.DisplayWindows.Keys.Contains(screen.DisplayScreen.DeviceName))
                {
                    tempDic.Add(screen.DisplayScreen.DeviceName, ScreenManger.DisplayWindows[screen.DisplayScreen.DeviceName]);
                }
                else
                {
                    DaPingDisplayWin win = new DaPingDisplayWin();
                    win.DataContext = screen;
                    tempDic.Add(screen.DisplayScreen.DeviceName, win);
                    ScreenManger.DisplayWindows.Add(screen.DisplayScreen.DeviceName, win);
                    win.Show();
                    ScreenHelper.ShowToScreen(screen.DisplayScreen, new WindowInteropHelper(win).Handle);
                    win.DisPlay(screen);
                }
            }
            string[] keys = ScreenManger.DisplayWindows.Keys.Except(tempDic.Keys).ToArray();
            foreach (var key in keys)
            {
                ScreenManger.DisplayWindows[key].Close();
                ScreenManger.DisplayWindows.Remove(key);
            }
            timer.Start();
        }

        public ObservableCollection<CustomScreenModel> ListScreen
        {
            get
            {
                return _model.ScreenList;
            }
        }

        public void SetUrlCtrlVisible(bool isEnabled)
        {
            foreach (var ctrl in itemsControl.Items)
            {
                (ctrl as CustomScreenModel).UrlIsEnabled = isEnabled;
            }
        }
    }
}
